import styled from 'styled-components';
import React, { CSSProperties, FC, useCallback, useEffect, useState } from 'react';
import { Button, Card, Table, Space, Collapse, Modal, Select } from 'antd';
import type { CollapseProps, } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';

import { dsFind, dsFindOne, ComparsionOperator, Project, ProjectApplication, dsDelete, dsBatchInsert } from '@/services/local';
import { DOMAIN_CLASS_IDENTIFIER, PROJECT_APPLICATION_CLASS_IDENTIFIER, PROJECT_CLASS_IDENTIFIER, PROJECT_DOMAIN_CLASS_IDENTIFIER, PROJECT_TASK_CLASS_IDENTIFIER, SCHEDULER_TASK_CLASS_IDENTIFIER } from '@/services/constants';
import { ProjectApplicationEditor, ProjectApplicationTable } from '../application';
import { confirm } from '@tauri-apps/plugin-dialog';

export interface ProjectPanelProps {
    style?: CSSProperties;
    projectIdentifier: string;
}

export const ProjectPanel: FC<ProjectPanelProps> = (props) => {

    const [project, setProject] = useState<Project | null>(null);

    useEffect(() => {
        dsFindOne(0, PROJECT_CLASS_IDENTIFIER, {
            attributes: [
                {
                    name: 'identifier',
                    operator: ComparsionOperator.Equal,
                    value: props.projectIdentifier
                }
            ]
        }).then((proj) => {
            setProject(proj);
        }).catch((err) => {
            console.error(err);
        });

    }, [props.projectIdentifier]);

    if (!project) {
        return (
            <Container></Container>
        );
    }

    return <Container>
        <Collapse items={[
            {
                key: '1',
                label: '基础配置',

                children: <Top>
                    <ProjectDomainsConfigPanel project={project}></ProjectDomainsConfigPanel>
                    {/* <ProjectDataSourcesConfigPanel project={project}></ProjectDataSourcesConfigPanel> */}
                    <ProjectWorkflowConfigPanel project={project}></ProjectWorkflowConfigPanel>
                </Top>,
            },
        ]} />
        <Bottom>
            <ProjectApplicationsConfigPanel project={project}></ProjectApplicationsConfigPanel>
        </Bottom>
    </Container>
}
interface ProjectDomainsConfigPanelProps {
    style?: CSSProperties;
    project: Project;
}

const ProjectDomainsConfigPanel: FC<ProjectDomainsConfigPanelProps> = (props) => {
    const navigate = useNavigate();

    const [loading, setLoading] = useState<boolean>(false);

    const [isModalOpen, setIsModalOpen] = useState(false);

    const [tasks, setTasks] = useState<Array<any>>([]);

    const [items, setItems] = useState<Array<string>>([]);

    const [selectValues, setSelectValues] = useState<Array<string>>([]);

    const [selected, setSelected] = useState<Project | null>(null);


    const refresh = async () => {
        setLoading(true);
        try {
            const { data: tasks } = await dsFind(0, DOMAIN_CLASS_IDENTIFIER, {});
            setTasks(tasks);

            const { total, data } = await dsFind(0, PROJECT_DOMAIN_CLASS_IDENTIFIER, {
                attributes: [{
                    name: 'project_identifier',
                    operator: ComparsionOperator.Equal,
                    value: props.project.identifier
                }]
            });
            setItems(data.map(item => item.domain_identifier));
        } catch (error) {
            console.error(error);
        }
        setLoading(false);
    };

    const columns = [
        {
            title: '标题',
            dataIndex: 'title',
            key: 'title',
            ellipsis: true,
        },
        {
            title: '操作',
            dataIndex: '操作',
            key: '操作',
            width: '120px',
            render: (_, record) => {
                return (
                    <Space size="middle">
                        <Button
                            type={'link'}
                            size={'small'}
                            onClick={async () => {
                                //
                                setSelected(record);
                                navigate(`/data/dataflow`);
                            }}
                        >编辑</Button>
                        <Button
                            type={'link'}
                            size={'small'}
                            onClick={async () => {
                                //
                                const confirmed2 = await confirm('确定从该工程中移除吗？', { title: '移除', kind: 'warning' });
                                if (confirmed2) {

                                    //
                                    await refresh();
                                }
                            }}
                        >移除</Button>
                    </Space>
                );
            }
        },
    ];

    useEffect(() => {
        refresh();
    }, []);

    return <Card style={{ width: '50%' }} title={'知识域配置'} size={'small'} extra={<Button type={'text'} icon={<PlusOutlined />}
        onClick={async () => {
            setIsModalOpen(true);
        }}></Button>} >
        <Table
            bordered
            loading={loading}
            rowKey={'identifier'}
            pagination={false}
            dataSource={tasks.filter(item => items.indexOf(item.identifier) >= 0)}
            columns={columns}
        />
        <Modal
            styles={{
                content: {
                    minWidth: '600px',
                    minHeight: '400px'
                }
            }}
            title="添加知识域"
            // footer={false}
            destroyOnClose={true}
            open={isModalOpen}
            onOk={async () => {
                //删除，再添加
                let res = await dsDelete(0, PROJECT_DOMAIN_CLASS_IDENTIFIER, {
                    attributes: [
                        {
                            name: 'project_identifier',
                            operator: ComparsionOperator.Equal,
                            value: props.project.identifier
                        }
                    ]
                });
                let insertRes = await dsBatchInsert(0, selectValues.map(item => {
                    return [PROJECT_DOMAIN_CLASS_IDENTIFIER, {
                        project_identifier: props.project.identifier,
                        domain_identifier: item
                    }];
                }));
                //刷新
                await refresh();
                setIsModalOpen(false);
            }} onCancel={async () => {
                //刷新
                await refresh();
                setIsModalOpen(false);
            }}>
            <label>选择知识域</label>
            <Select
                mode="multiple"
                defaultValue={[]}
                value={selectValues}
                style={{ width: '100%' }}
                onChange={(keys) => {
                    setSelectValues(keys);
                }}
                options={tasks.map(item => {
                    return { label: item.name || item.title, value: item.identifier };
                })}
            />
        </Modal>
    </Card>
}

interface ProjectDataSourcesConfigPanelProps {
    style?: CSSProperties;
    project: Project;
}
const ProjectDataSourcesConfigPanel: FC<ProjectDataSourcesConfigPanelProps> = (props) => {

    const [loading, setLoading] = useState<boolean>(false);

    const [isModalOpen, setIsModalOpen] = useState(false);

    const [items, setItems] = useState<Array<ProjectApplication>>([]);

    const [total, setTotal] = useState<number>(0);

    return <Card style={{ width: '50%' }} title={'数据源配置'} size={'small'} extra={<Button type={'text'} icon={<PlusOutlined />}></Button>} >


    </Card>
}
interface ProjectApplicationsConfigPanelProps {
    style?: CSSProperties;
    project: Project;
}

const ProjectApplicationsConfigPanel: FC<ProjectApplicationsConfigPanelProps> = (props) => {

    const [loading, setLoading] = useState<boolean>(false);

    return <>
        <Card style={{ width: '100%' }}
            title={'应用列表'} size={'small'}
            extra={<></>}
        >
            <ProjectApplicationTable projectIdentifier={props.project?.identifier}></ProjectApplicationTable>
        </Card>
    </>
}



interface ProjectWorkflowConfigPanelProps {
    style?: CSSProperties;
    project: Project;
}

const ProjectWorkflowConfigPanel: FC<ProjectWorkflowConfigPanelProps> = (props) => {

    const navigate = useNavigate();

    const [loading, setLoading] = useState<boolean>(false);

    const [isModalOpen, setIsModalOpen] = useState(false);

    const [tasks, setTasks] = useState<Array<any>>([]);

    const [items, setItems] = useState<Array<string>>([]);

    const [selectValues, setSelectValues] = useState<Array<string>>([]);

    const [selected, setSelected] = useState<Project | null>(null);

    const refresh = async () => {
        setLoading(true);
        try {
            const { data: tasks } = await dsFind(0, SCHEDULER_TASK_CLASS_IDENTIFIER, {});
            setTasks(tasks);

            const { total, data } = await dsFind(0, PROJECT_TASK_CLASS_IDENTIFIER, {
                attributes: [{
                    name: 'project_identifier',
                    operator: ComparsionOperator.Equal,
                    value: props.project.identifier
                }]
            });
            setItems(data.map(item => item.task_identifier));
        } catch (error) {
            console.error(error);
        }
        setLoading(false);
    };

    const columns = [
        {
            title: '标题',
            dataIndex: 'title',
            key: 'title',
            ellipsis: true,
        },
        {
            title: '操作',
            dataIndex: '操作',
            key: '操作',
            width: '120px',
            render: (_, record) => {
                return (
                    <Space size="middle">
                        <Button
                            type={'link'}
                            size={'small'}
                            onClick={async () => {
                                //
                                setSelected(record);
                                navigate(`/data/dataflow`);
                            }}
                        >编辑</Button>
                        <Button
                            type={'link'}
                            size={'small'}
                            onClick={async () => {
                                //
                                const confirmed2 = await confirm('确定从该工程中移除吗？', { title: '移除', kind: 'warning' });
                                if (confirmed2) {

                                    //
                                    await refresh();
                                }
                            }}
                        >移除</Button>
                    </Space>
                );
            }
        },
    ];

    useEffect(() => {
        refresh();
    }, []);

    return <Card
        style={{ width: '50%' }}
        title={'数据流配置'}
        size={'small'}
        extra={<Button type={'text'} icon={<PlusOutlined />}
            onClick={async () => {
                setIsModalOpen(true);
            }}></Button>}
    >
        <Table
            bordered
            loading={loading}
            rowKey={'identifier'}
            pagination={false}
            dataSource={tasks.filter(item => items.indexOf(item.identifier) >= 0)}
            columns={columns}
        />
        <Modal
            styles={{
                content: {
                    minWidth: '600px',
                    minHeight: '400px'
                }
            }}
            title="添加数据流"
            // footer={false}
            destroyOnClose={true}
            open={isModalOpen}
            onOk={async () => {
                //删除，再添加
                let res = await dsDelete(0, PROJECT_TASK_CLASS_IDENTIFIER, {
                    attributes: [
                        {
                            name: 'project_identifier',
                            operator: ComparsionOperator.Equal,
                            value: props.project.identifier
                        }
                    ]
                });
                let insertRes = await dsBatchInsert(0, selectValues.map(item => {
                    return [PROJECT_TASK_CLASS_IDENTIFIER, {
                        project_identifier: props.project.identifier,
                        task_identifier: item
                    }];
                }));
                //刷新
                await refresh();
                setIsModalOpen(false);
            }} onCancel={async () => {
                //刷新
                await refresh();
                setIsModalOpen(false);
            }}>
            <label>选择数据流</label>
            <Select
                mode="multiple"
                defaultValue={[]}
                value={selectValues}
                style={{ width: '100%' }}
                onChange={(keys) => {
                    setSelectValues(keys);
                }}
                options={tasks.map(item => {
                    return { label: item.name || item.title, value: item.identifier };
                })}
            />
        </Modal>
    </Card>
}


const Container = styled.div`
    height: 100%;
    width: 100%;
    padding:6px;
    display: flex;
    flex-direction: column;
    gap:6px;
`;

const Top = styled.div`
    width: 100%;
    height:300px;
    display: flex;
    flex-direction: row;
    gap:6px;
`;
const Bottom = styled.div`
    width: 100%;
    flex: 1;
    display: flex;
    flex-direction: row;
    gap:6px;
`;